package org.nowcoder.leetcode.BTree;

/**
 * Title  : 108. Convert Sorted Array to Binary Search Tree
 * Source : https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/description/
 * Author : XrazYang
 * Date   : 2024-04-24
 */

public class LeetCode_108 {
    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode sortedArrayToBST(int[] nums) {
        return sortedArrayToBST2(nums, 0, nums.length - 1);
    }

    public TreeNode sortedArrayToBST2(int[] nums, int left, int right) {
        if (left > right) return null;
        int mid = left + ((right - left) >> 1);
        TreeNode root = new TreeNode(nums[mid]);
        root.left = sortedArrayToBST2(nums, left, mid - 1);
        root.right = sortedArrayToBST2(nums, mid + 1, right);
        return root;
    }
}

